<?php
class Translate extends AppModel{
    public $useTable  = 'translate';
    
    public function get_translate()
    {
        $sql = "SELECT VN.translate_id, VN.key_word, VN.translate, EN.translate
                FROM
                (
                	SELECT *
                	FROM translate WHERE lang_code = 'vn'
                ) VN
                LEFT JOIN
                (
                	SELECT *
                	FROM translate WHERE lang_code = 'en'
                ) EN
                ON VN.key_word = EN.key_word";
        $translates = $this->query($sql);
        
        return $translates;
    }
    
    function add($data = array())
    {
        if(!isset($data['translate_id']))
        {
            $sql = "SELECT MAX(translate_id) AS max_translate_id
                FROM translate";
            $rs = $this->query($sql);
            $max_translate_id = $rs[0][0]['max_translate_id'];
            $max_translate_id = $max_translate_id == '' ? 1 : $max_translate_id+1;
            $data['translate_id'] = $max_translate_id;
        }
        else
        {
            $this->del($data['translate_id'], $data['lang_code']);
        }
        $this->create();
        $this->save($data);
		return $this->getLastInsertId();
    }
    
    function del($translate_id = null, $lang_code = null)
    {
       $del_lang = $lang_code == null ? '' : " AND lang_code = '$lang_code' ";
       $sql = "DELETE FROM translate WHERE translate_id = '$translate_id' $del_lang";
   	    return $this->query($sql);
    }
    
    public function get_translate_by_id($translate_id = "")
    {
    	if($translate_id == "")
    		return null;

    	$sql = "SELECT * FROM translate WHERE translate_id = '$translate_id'";
    	$data = $this->query($sql);
        $result = array();
        foreach ($data as $value) {
			$lang_code = $value['translate']['lang_code'];
            $result['key_word'] = $value['translate']['key_word'];
			$result[$lang_code] = $value['translate']['translate'];

		}
		return $result;
    }
    
    public function get_translate_by_keyword($key_word = "")
    {
    	if($key_word == "")
    		return null;

    	$sql = "SELECT * FROM translate WHERE key_word = '$key_word'";
    	$data = $this->query($sql);
        $result = array();
        foreach ($data as $value) {
			$lang_code = $value['translate']['lang_code'];
            $result['key_word'] = $value['translate']['key_word'];
			$result[$lang_code] = $value['translate']['translate'];

		}
		return $result;
    }
}